package com.crazymo.bitmapbase64;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.StringDef;
import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;


public class BitmapUtil {

    public static String getSDPath() {
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            return Environment.getExternalStorageDirectory().getPath();
        } else {
            return "";
        }
    }

    /**
     * 将图片转换成Base64编码的字符串
     * @param path Bitmap的全路径
     */
    public static String bitmap2Base64(String path){
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.NO_CLOSE);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    /**
     * 将Base64编码字符串转为图片
     * @param base64Str 源编码的Base64字符串
     * @return bitmap
     */
    public static Bitmap base64ToBitmap(String base64Str) {
        byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);
        if(data!=null && data.length>0) {
            for (int i = 0; i < data.length; i++) {
                if (data[i] < 0) {
                    //调整异常数据
                    data[i] += 256;
                }
            }
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        }
        return null;
    }

    /**
     * 将Base64编码转换为Bitmap 并保存
     * @param base64Str 源编码的Base64字符串
     * @param parentDir Bitmap保存的父目录路径
     * @param name Bitmap 的名称，不需要带上后缀
     * @return Bitmap的全路径名称
     */
    public static String base64ToBitmap(String base64Str,String parentDir, String name,@ImageType String type ) {
        String path="";
        byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);
        for (int i = 0; i < data.length; i++) {
            if(data[i] < 0){
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            File parentFile = new File(parentDir);
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            File jpgFile = new File(parentDir, name + type);
            os = new FileOutputStream(jpgFile);
            os.write(data);
            os.flush();
            path= jpgFile.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return path;
    }

    public static byte[] bitmap2Bytes(android.graphics.Bitmap bitmap) {
        ByteArrayOutputStream byteArrOutStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrOutStream);
        return byteArrOutStream.toByteArray();
    }

    public static Bitmap bytes2Bitmap(@NonNull byte[] bytes) {
        if (bytes.length != 0) {
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
        return null;
    }

    @StringDef({ImageType.JPG,ImageType.PNG,ImageType.BITMAP})
    @Retention(RetentionPolicy.SOURCE)
    public @interface ImageType{
        String PNG=".png";
        String JPG=".jpg";
        String BITMAP=".bmp";
    }
}
